<?php

/**
 * category_content actions.
 *
 * @package    master_directory
 * @subpackage category_content
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class category_contentActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
     $this->master_directories = $this->filterCategoryDirectories();   
     
     $categoryId = $request->getParameter('category_id');
     $directory = ($categoryId == null) ? $this->master_directories[0] : Doctrine_Core::getTable('Category')->find(array($categoryId))->getMasterDirectory();
     
    // $this->category_content_roots = ($categoryId != null) ? Doctrine_Core::getTable ( 'CategoryContent' )->getCategoryContentRootsByCategoryId($categoryId) : null;
     
     $this->categories = $this->filterCategories($directory->getCategory());
     
     $this->selectedDirectoryId = $directory->getId();
     $this->selectedCategoryId = ($categoryId == null) ?  $this->categories[0]->getId() : $categoryId;
     
     $this->info_array = $this->getUser()->getAttribute("info_array") != null ? $this->getUser()->getAttribute("info_array") : null;

     $this->getUser()->getAttributeHolder()->remove('info_array');     
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->category_content = Doctrine_Core::getTable('CategoryContent')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->category_content);
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new CategoryContentForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new CategoryContentForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($category_content = Doctrine_Core::getTable('CategoryContent')->find(array($request->getParameter('id'))), sprintf('Object category_content does not exist (%s).', $request->getParameter('id')));
    $this->form = new CategoryContentForm($category_content);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($category_content = Doctrine_Core::getTable('CategoryContent')->find(array($request->getParameter('id'))), sprintf('Object category_content does not exist (%s).', $request->getParameter('id')));
    $this->form = new CategoryContentForm($category_content);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
   // $request->checkCSRFProtection();

    $this->forward404Unless($category_content = Doctrine_Core::getTable('CategoryContent')->find(array($request->getParameter('id'))), sprintf('Object category_content does not exist (%s).', $request->getParameter('id')));
    $category_content->delete();

    $this->redirect('category_content/index');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $category_content = $form->save();

      //$this->redirect('category_content/edit?id='.$category_content->getId());
    }
  }
  
   public function executeLoadCategories(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    
    $directory = Doctrine_Core::getTable('MasterDirectory')->find(array($request->getParameter('directory_id')));
    
    $this->master_directories = $this->filterCategoryDirectories();   
    
    $this->categories = $this->filterCategories($directory->getCategory());
   
    return $this->renderPartial('category_level', array('categories' => $this->categories, 'master_directories' => $this->master_directories, 'selectedDirectoryId' => $request->getParameter('directory_id')));

  }  
  
  public function executeGetCSV(sfWebRequest $request){
  	$category_id = $request->getParameter('level_category_id');
  	
  	$category = Doctrine_Core::getTable('Category')->find(array($category_id));
  	
  	$tree_depth = Doctrine_Core::getTable('Level')->getDepth($category_id);
  	
  	
  	
	$downloadFile = sfConfig::get('sf_upload_dir') . '/csv/' . $category->getName() . "-headers.csv";
  	$handle = fopen($downloadFile,"w+") or die ("unable to open file");
  	
  	
  	$headersArray = array();
  	for ($i = 1; $i <= $tree_depth; $i++){
  		array_push($headersArray, "Level " . $i);
  		array_push($headersArray, "DESCRIPTION");
  	}

  	
  	fputcsv($handle, $headersArray);  	
  	
  	fclose($handle);
  	
    $this->prepareContent($downloadFile);
    
    
    
	return sfView::NONE;  	
  	
  }
  
  
  public function executeSaveCategoryContent(sfWebRequest $request){
  	// if ( $request->getFileSize("csv_file")){
  	 	$filename = uniqid("file_").".csv";
  	 	
  	 	
  	 	$uploadDir = sfConfig::get('sf_upload_dir') . '/csv';
  	 	
  	 	
  	 	$uploaded_file = $request->getFiles('fileInput');
  	 	
  	 	
  	 	move_uploaded_file($uploaded_file["tmp_name"], $uploadDir . "/" . $filename );
  	 	
        $csvFile = sfConfig::get('sf_upload_dir').'/csv/' .$filename;
        
	  	$category_id = $request->getParameter('h_category_id');
	  	
	  	$tree_deph = Doctrine_Core::getTable ( 'Level' )->getDepth($category_id);
	  	
	  	
	  	$category_content_roots = Doctrine_Core::getTable ( 'CategoryContent' )->getCategoryContentRootsByCategoryId($category_id);

	  	foreach ($category_content_roots as $category_content_root){
	  		Doctrine_Core::getTable ( 'CategoryContent' )->deleteChildren($category_content_root);
	  	}
	  	
	  	
	  	$existing_contents = Doctrine_Core::getTable ( 'CategoryContent' )->getCategoryContentByCategoryId($category_id);
	  	
	  	
	  	foreach ($existing_contents as $existing_content){
	  		$existing_content->delete();
	  	}
	  	
	  	$file_handle = fopen($csvFile, "r");
	  	
	  	$info_array = array();
	  	
	  	
	  	for ($i = 0; $i < $tree_deph; $i++) {
	  		$info_array[$i] = 0;
	  	}
	  	
	  	$previous_content_line = array();
	  	
		while (!feof($file_handle) ) {
			$parentId = null;
			$line = fgetcsv($file_handle, 1024);
			if($line[0] != null &&  $line[0] != '' &&  $line[0] != 'Level 1' ){
				//for ($i = 0; $i < $column_count; $i++) {
				$i = 0;
				
				while ($i < 2*$tree_deph && $line[$i] != null &&  $line[$i] != ''){
					$category_content = null;
					if(count($previous_content_line) == $tree_deph){
						$category_content = ($previous_content_line[$i/2]->getName() == $line[$i]) ? $previous_content_line[$i/2] : Doctrine_Core::getTable ( 'CategoryContent' )->getCategoryContent($category_id, $line[$i]);
					}else{
						$category_content = Doctrine_Core::getTable ( 'CategoryContent' )->getCategoryContent($category_id, $line[$i]);
					}
					if($category_content == null){
						$category_content = new CategoryContent();
						$category_content->setName($line[$i]);
						$category_content->setDescription($line[$i + 1]);
						$category_content->setCategoryId($category_id);
						$category_content->setParentId($parentId);
						$category_content->save();
						
						//$temp_info_array_elem = $info_array[$i/2];
						$info_array[$i/2] = $info_array[$i/2] + 1;
					}
					$previous_content_line[$i/2] = $category_content;
					$parentId = $category_content->getId();
				$i += 2;	
				}
			}
		}
  	 //}
  	 
		
		$this->getUser()->setAttribute("info_array", $info_array) ;
  	 
		return $this->redirect('category_content/index?category_id=' . $category_id);
  }
  
  
  protected function prepareContent($downloadFile){
  	//header("Content-Type: application/vnd.ms-excel, charset=UTF-8");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: binary");
    header("Content-Disposition: attachment;filename=".substr($downloadFile, strrpos($downloadFile, "/")+1, strlen($downloadFile)- strrpos($downloadFile, "/")+1));
    header("Content-Length: ".filesize($downloadFile));
    header('Content-Encoding: UTF-8');
	header('Content-Type: text/csv; charset=UTF-8;');
    header("Pragma: no-cache");
    header("Expires: 0");
    readfile($downloadFile);
  }
  
  //to retrieve a list of directories with one or more categories with levels
  protected function filterCategoryDirectories(){
  	$directories_with_categories = array();
  	$levels = Doctrine_Core::getTable('Level')->loadAll();
  	foreach ($levels as $level){
  		array_push($directories_with_categories, $level->getCategory()->getMasterDirectory());
  	}
  	
  	return array_unique($directories_with_categories);
  }
  
  protected function filterCategories($categories){
  	$categories_with_levels = array();
  	foreach ($categories as $category){
  		if(count($category->getLevel()) > 0){
  			array_push($categories_with_levels, $category);
  		}
  	}
  	return $categories_with_levels;
  }
  
  
}
